<template>
  <div class="app-container">
    <el-card class="box-card" shadow="never" style="border:0px;">
      <div slot="header" style="color:#303133;font-size:14px;font-weight:bold;">
        <span>角色管理</span>
      </div>
      <div class="filter-container">
        <div class="left">
          <el-form :inline="true" class="demo-form-inline" size="medium" label-position="right">
            <el-form-item label="角色名称：">
              <el-input v-model="listQuery.name" clearable class="filter-item" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="开始时间：">
              <el-date-picker
                class="date_item"
                v-model="listQuery.startCreateTime"
                type="date"
                placeholder="选择开始时间"
                align="right"
                value-format="yyyy-MM-dd"
                @change="loadData()"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间：">
              <el-date-picker
                class="date_item"
                v-model="listQuery.endCreateTime"
                type="date"
                placeholder="选择结束时间"
                align="right"
                value-format="yyyy-MM-dd"
                @change="loadData()"
              >
              </el-date-picker>
            </el-form-item>
          </el-form>
        </div>
        <div class="right">
          <el-button type="primary"  @click="loadData">查询</el-button>
          <el-button  @click="resetQueryForm">重置</el-button>
        </div>
      </div>

      <vxe-toolbar ref="xToolbar">
        <template #buttons>
          <el-button v-permission="'system:repay-list-menu:add'"  type="text" icon="el-icon-plus" @click="addEvent">新增</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        :data="data"
        ref="roleTable"
        :radio-config="{ highlight: true }"
        v-loading="loading"
        border="none"
        highlight-hover-row
        show-header-overflow
        show-overflow
        align="center"
        :header-cell-style="{background:'#F7F7F8',color:'#606266'}"
        @cell-dblclick="cellDblclick"
      >
        <vxe-table-column title="角色名称" field="name" />
        <vxe-table-column title="角色描述" field="description" />
        <vxe-table-column title="创建日期" field="createTime" />
        <vxe-table-column title="权限配置" width="300px">
          <template v-slot="{ row }">
            <el-button type="primary" icon="fa fa-edit" @click="openAssignPermissionModel(row.id,row.name)" size="mini">权限配置</el-button>
          </template>
        </vxe-table-column>
        <vxe-table-column title="操作" width="300px">
          <template v-slot="{ row }">
            <el-button  type="text" @click="editPermissions(row)" >编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button  type="text" @click="deleteCheckedRole(row)" >删除</el-button>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-modal
        @close="closeModal"
        v-model="modalUpdate.show"
        width="600px"
        height="400px"
        :title="modalUpdate.edit ? '修改&保存' : '新增&保存'"
      >
        <template v-slot>
          <vxe-form :data="modalUpdate.row" title-align="right" title-width="190">
            <vxe-form-item title="角色名称" field="name">
              <vxe-input v-model="modalUpdate.row.name" placeholder="角色名称" clearable style="width:280px"></vxe-input>
            </vxe-form-item>
            <vxe-form-item title="角色描述" field="description">
              <vxe-textarea v-model="modalUpdate.row.description" placeholder="不超过200字符" style="height:190px;width:280px" maxlength="200" show-word-count></vxe-textarea>
            </vxe-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="8">
                <vxe-form-item>
                  <template v-slot>
                    <el-button type="primary" @click="saveOrUpdateModalSubmit">提交</el-button>
                    <el-button @click="closeModalUpdate" >取消</el-button>
                  </template>
                </vxe-form-item>
              </el-col>
            </el-row>
          </vxe-form>
        </template>
      </vxe-modal>
      <!-- :title="'权限配置'" -->
      <vxe-modal
        v-model="assignPermission.show"
        width="60%"
        height="60%"
        :title="perSittleTitle"
        :position="{left: 400}"
        draggable="false"
      >
        <el-tree
          :data="assignPermissionData"
          :default-checked-keys="assignPermissionCheckedData"
          show-checkbox
          node-key="id"
          ref="tree"
          highlight-current
          accordion
          :props="defaultProps">
        </el-tree>
        <div class="buttons submit-permission-button">
          <el-button type="primary" @click="saveAssignPermission">保存</el-button>
          <el-button @click="cancelAssignPermissionModel()">取消</el-button>
        </div>
      </vxe-modal>
    </el-card>
    <vxe-pager
      class="pager"
      @page-change="changePage"
      :current-page.sync="listQuery.pageNo"
      :page-size.sync="listQuery.pageSize"
      :total="total"
      :page-sizes="[10, 30, 50,100]"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
    >
    </vxe-pager>
  </div>
</template>

<script>
  import {
    queryByPaging,
    saveOrUpdate,
    deleteById,
    listTree,
  } from './tools';
  import { getPermissionByRoleId,saveAssignPermissionRole } from '@/api/role';
  export default {
    name: 'RoleManagement',
    data() {
      return {
        total: 0,
        ifOpen: false,
        defaultProps: {
          children: 'children',
          label: 'displayName',
        },
        roleChecked: {},
        listQuery: {
          pageNo: 1,
          pageSize: 10,
          name: undefined,
          startCreateTime: undefined,
          endCreateTime: undefined,
          available: 1
        },
        modalUpdate: {
          show: false,
          edit: false,
          row: {},
          originRow: {}
        },
        perSittleTitle: undefined,
        assignPermission: {
          show: false
        },

        data: [],
        checkRowKeys: undefined,
        assignPermissionData: [],
        assignPermissionCheckedData: [],
        assignPermissionParam: {
          perIds: undefined,
          roleId: undefined
        },
        loading: true,
        defaultProps: {
          children: 'children',
          label: 'displayName',
          value: 'id'

        }
      }
    },
    mounted() {
      this.loadData();
    },
    methods: {
      getTreeExpansionEvent () {
        let selectRow = this.$refs.tree.getRadioRecord()
        this.$XModal.alert(selectRow ? selectRow.displayName : 'null')
      },
      getTreeExpansionEvent() {
        let treeExpandRecords = this.$refs.tree.getTreeExpandRecords()
        this.$XModal.alert(treeExpandRecords.length)
      },
      // 遍历树
      foreachTree(data,IDArr){
        var children = data.children;

        if (IDArr.includes(data.id)) {
          // this.$refs.tree.setCheckboxRow(data, true);
          console.log("11111111111" + data.id);
          this.$refs.tree.setCheckboxRow(data,true);
        }
        if (children != undefined) {
          children.forEach(row => {
            this.foreachTree(row,IDArr);
          });
        }
      },
      // 打开权限配置窗口
      openAssignPermissionModel(roleId,roleName) {
        this.perSittleTitle = roleName+"权限配置";
        this.assignPermission.show = true;
        getPermissionByRoleId(roleId).then((data) => {
          this.assignPermissionCheckedData = data.data;
        });

        listTree(this.listQuery).then((data) => {
          // var data1 = data.data.children;
          // this.foreachTree(data.data,IDArr);
          this.assignPermissionData = data.data.children;
        });
        this.assignPermissionParam.id = roleId;
      },

      closeModalUpdate(){
        this.resetModal;
        this.modalUpdate.show = false;
        this.modalUpdate.edit = true;
      },

      // 关闭权限配置窗口
      cancelAssignPermissionModel() {
        this.resetModal;
        this.assignPermission.show = false;
      },

      // 保存权限
      saveAssignPermission() {
        this.loading = true;
        //选中的子节点
        let selectRecordsChildren = this.$refs.tree.getCheckedKeys(true)
        //选中子节点的父节点
        let selectRecordsParent = this.$refs.tree.getHalfCheckedKeys(true)
        let selectRecords =  selectRecordsChildren.concat(selectRecordsParent)
        console.log(selectRecords)
        this.assignPermissionParam.sysPermissions = selectRecords;
        saveAssignPermissionRole(this.assignPermissionParam).then((data) => {
          this.$notify.success({title: '成功',message: '操作成功',});
          this.cancelAssignPermissionModel();
          this.queryList();
        }).catch(() => {
          this.loading = false;
        })
      },

      // 角色列表查询
      queryList() {
        this.loading = true;
        listTree(this.listQuery).then((data) => {
          this.assignPermissionData = data.data.children;
          console.log('响应数据:%o', data);
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        })
      },

      // 按照角色id查询该角色拥有的权限id
      getPermissionByRoleId(roleId) {
        getPermissionByRoleId(roleId).then((data) => {
          this.checkRowKeys = data.data;
          console.log('响应数据111:%o', data);
        });
      },


      isEditing() {
        return this.modalUpdate.edit;
      },
      isIncrease() {
        return !this.modalUpdate.edit;
      },
      // saveOrUpdateModalSubmit() {
      //   const that = this;
      //   saveOrUpdate(this.modalUpdate.row).then(function (data) {
      //     if (that.isEditing()) {
      //       const index = that.data.findIndex((ele) => {
      //         return ele.id == that.modalUpdate.originRow.id;
      //       });
      //       if (index >= 0) {
      //         that.data.splice(index, 1, that.modalUpdate.row);
      //       }
      //     }
      //     if (that.isIncrease()) {
      //       that.data.push(data.data);
      //     }
      //     this.loadData();
      //     // that.closeModal();

      //   });
      // },

      saveOrUpdateModalSubmit() {
        if(this.modalUpdate.row.name == undefined){
          this.$message.error('角色名称必填哦');
          return;
        }
        saveOrUpdate(this.modalUpdate.row).then((data) => {
          this.$notify.success({title: '成功',message: '操作成功',});
          this.loadData();
          this.closeModal();
        })
      },




      editPermissions(row) {
        this.modalUpdate.row = row;
        this.modalUpdate.originRow = { ...this.roleChecked };
        this.modalUpdate.show = true;
        this.modalUpdate.edit = true;
      },
      deleteCheckedRole(row) {
        if (this.roleChecked.id == this.$store.getters.id) {
          this.$XModal.alert({ message: '不能删除自己的角色', status: 'error' });
          return;
        }
        this.$XModal.confirm(`确定删除${row.displayName}吗`).then((type) => {
          if (type === 'confirm') {
            this.loading = true;
            deleteById(row.id).then((data) => {
              this.$notify.success({title: '成功',message: '删除成功',});
              this.loadData();
            })
          }
        });
      },

      changePage() {
        this.loadData();
      },
      addEvent() {
        this.modalUpdate.show = true;
        this.modalUpdate.edit = false;
        this.modalUpdate.row = {};
      },
      resetModal() {
        const resetRow = this.modalUpdate.originRow ? this.modalUpdate.originRow : {};
        this.modalUpdate.row = { ...resetRow };
      },
      closeModal() {
        this.modalUpdate.row = {};
        this.modalUpdate.originRow = {};
        this.modalUpdate.show = false;
        this.modalUpdate.edit = false;
      },
      loadData() {
        this.loading = true;
        queryByPaging(this.listQuery.pageNo, this.listQuery.pageSize, this.listQuery)
          .then((data) => {
            this.data = data.data;
            this.total = data.total;
            console.log('响应数据:%o', data);
            this.loading = false;
          }).catch(() => {
          this.loading = false;
        })
      },

      resetQueryForm() {
        this.listQuery = {
          pageNo: 1,
          pageSize: 10,
          name: undefined,
          startCreateTime: undefined,
          endCreateTime: undefined
        };
        this.loadData();
      },
      cellDblclick({row,rowIndex,column,columnIndex,cell},event) {
        let _this = this;
        this.$copyText(event.target.innerText).then(function() {
          _this.$message.info('复制成功');
        });
      }


    },
  };
</script>

<style lang="scss" scoped>
  .toolbar-form {
    padding-top: 10px;
    padding-left: 10px;
  }

  .vxe-table {
    margin-left: 10px;
  }

  //修改toolbar的高度固定的问题
  .vxe-toolbar {
    margin: 10px;
  }
</style>

<style lang="css" scoped>
  .filter-container {
    display: flex;
    justify-content: space-between;
  }

  .pager{
    position: fixed;
    bottom: 0;
    right: 28px;
    background-color: #FAFAFB;
    z-index: 2;
    height: 40px;
    width: calc(100% - 260px);
  }

  .submit-permission-button{
    position: fixed;
    bottom: 25%;
    right: 25%;
  }

  .right >>> .el-button--primary,.el-button--default {
    padding: 10px 20px;
  }

  .vxe-table--render-default >>> .el-button--text{
    color: #2b7bfb;
  }
  .app-container >>> .vxe-table--render-default,.vxe-pager {
    font-family: PingFangSC, Arial, Helvetica, sans-serif;
  }

  .left {
    flex: 14;
    display: flex;
    flex-flow: row wrap;
    margin-right: 20px;
  }
  .left >>> .el-form {
    width: 100%;
  }
  .left >>> .el-form .el-form-item {
    display: flex;
    flex-flow: row nowrap;
    width: 30%;
    margin-right: 3%;
    float: left;
    margin-bottom: 14px;
  }

  .left >>> .el-form .el-form-item .el-form-item__label {
    font-weight: 500;
    color: #606266;
    text-align: left;
    /* flex: 1; */
  }

  .left >>> .el-form .el-form-item .el-form-item__content {
    flex: 1;
    /*超出部分隐藏*/
    text-overflow: ellipsis;
    /* 超出部分显示省略号 */
    white-space: nowrap;
    /*规定段落中的文本不进行换行 */
    width: 100%;
  }
  .date_item {
    width: 100%;
  }
  .right {
    flex: 2;
    display: flex;
    flex-flow: row nowrap;
    align-items: flex-end;
    /* margin-top: 30px; */
    margin-right: 30px;
    /* margin-bottom: 30px; */
  }
</style>

